const fs = require('fs')

const originFile = './Localizable.strings'
// const originFile = './demo.strings'
const outputFile = './result.yaml'

fs.readFile(originFile, 'utf-8',(err, data) => {
    data = convertAnnotation(data) // 替换多行注释
    data = convertSingleAnnotation(data) // 替换单行注释
    data = clearQuot(data) // 去除引号
    
    data = fomatYaml(data)
    data = data.replace(/=/g, ':') 
    fs.writeFile(outputFile, data, err => {
        if(err) throw err;
        console.log('convert ok');
    })
})


// 查找并替换多行注释部分
function convertAnnotation(text) {
    const pattern = /\/\*[\s\S]*?\*\//g
    let catchArr = []
    let temp = []
    while((temp = pattern.exec(text)) !== null){
        temp.lastIndex = pattern.lastIndex;
        catchArr.unshift(temp)
    }
    catchArr.forEach(ele => {
        console.log(ele[0]);
        // 替换 /* */ 为空
        let temp1 = ele[0].replace(/[(\\\*)(\*\/)]/g, '')
        // 增加 yaml 注释符
        let insert = '#' + temp1.replace(/\n/g, '\n#')
        text = text.replace(ele[0], insert)
    });

    return text;
}
// 查找替换单行注释部分
function convertSingleAnnotation(text){
    console.log(typeof text);
    return text.replace(/\/\//g, '#')
}


function clearQuot(text){
    return text.replace(/"/g, '')
}

function fomatYaml(text){
    const pattern = /\n\w+?_/g;
    let catchArr = [];
    let temp = [];
    while((temp = pattern.exec(text))!==null){
        catchArr.push(temp)
        // console.log(temp[0] + temp.index);
    }
    const fomatArr = isEqually(catchArr.map(val => val[0]))
    fomatArr.forEach(ele => {
        if(ele !== '  '){
            let tempele = ele.replace(/_/, '') + ':\n  '
            text = text.replace(ele, tempele)
        }
    });
    fomatArr.forEach(ele => {
        if(ele !== '  '){
            let tempele = '\n  '
            let tempPattert = new RegExp(ele, 'g')
            text = text.replace(tempPattert, tempele)
        }
    });
    return text

}

// 判断连续相等, 返回一个去除相等的数组
function isEqually(arr){
    let origin = arr[0]
    for(let i = 1; i < arr.length; i++){
        if(origin === arr[i] ){
            arr[i] = '  ' // 两个空格
        }else{
            origin = arr[i];
        }
    }

    return arr;
}